package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.help.subform.TransferSubFormHelper;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.PaymentSheetUserDao;
import com.xbongbong.saas.domain.entity.PaymentSheetUserEntity;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.enums.subform.PaymentSheetTeamEnum;
import com.xbongbong.saas.model.PaymentSheetUserModel;
import com.xbongbong.sys.domain.entity.UserEntity;
import org.elasticsearch.action.support.WriteRequest;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author 徐俊杰
 * @date 2020/2/13 16:50
 * @since v1.0
 */
@Component
@Service("paymentSheetUserModel")
public class PaymentSheetUserModelImpl implements PaymentSheetUserModel {
    @Resource
    private PaymentSheetUserDao paymentSheetUserDao;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private TransferSubFormHelper transferSubFormHelper;
    
    @Override
    public Integer insert(PaymentSheetUserEntity entity) throws XbbException {
        paymentSheetUserDao.insert(entity);
        PaasFormDataEntity paasFormDataEntity = transferSubFormHelper.transferUserTeamToFormData(IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_TEAM, entity);
        InsertDTO saveDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_TEAM);
//        InsertDTO insertDTO = new InsertDTO();
//        insertDTO.setWaitUntil(WriteRequest.RefreshPolicy.NONE);
//        insertDTO.setEsId(entity.getCorpid() + "_" + entity.getId());
//        insertDTO.setParent(entity.getCorpid() + "_" + entity.getDataId());
//        insertDTO.setSource(BeanUtil.convertBean2Map(entity, false, true));
//        insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_TEAM);
        paasEsModel.insert(saveDTO);
        return null;
    }
    
    @Override
    public Integer update(PaymentSheetUserEntity entity) throws XbbException {
        long now = DateTimeUtil.getInt();
        entity.setUpdateTime(now);
        Integer result = paymentSheetUserDao.update(entity);
        PaasFormDataEntity paasFormDataEntity = transferSubFormHelper.transferUserTeamToFormData(IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_TEAM, entity);
        InsertDTO saveDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_TEAM);
        paasEsModel.update(saveDTO);
//        paasEsModel.update(entity,IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_TEAM,entity.getCorpid(),entity.getId(),entity.getDataId());
        return result;
    }
    
    @Override
    public List<PaymentSheetUserEntity> findEntitys(Map<String, Object> param) {
        return paymentSheetUserDao.findEntitys(param);
    }
    
    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return paymentSheetUserDao.getEntitysCount(param);
    }

    @Override
    public List findEntitysWithoutSub(Map<String, Object> param) {
        return null;
    }

    @Override
    public Integer save(PaymentSheetUserEntity paymentUserEntity) throws XbbException {
        return null;
    }
    
    @Override
    public PaymentSheetUserEntity getByKey(Long key, String corpid) {
        return paymentSheetUserDao.getByKey(key, corpid);
    }
    
    @Override
    public List<PaymentSheetUserEntity> findAllEntitys(Map<String, Object> param) {
        return null;
    }
    
    @Override
    public List<PaymentSheetUserEntity> getPaymentSheetUserIdList(String corpid, Long paymentSheetId, Integer isMain) {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, corpid);
        param.put("dataId", paymentSheetId);
        param.put("isMain", isMain);
        param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        return findEntitys(param);
    }
    
    @Override
    public List<String> getContractUserIdList(String corpid, List<String> contractIds, Integer isMain) {
       return null;
    }
    
    @Override
    public void delete(PaymentSheetUserEntity paymentUserEntity) throws XbbException {
        paymentUserEntity.setDel(1);
        paymentUserEntity.setUpdateTime((long) DateUtil.getInt());
        paymentSheetUserDao.update(paymentUserEntity);
        paasEsModel.delete(paymentUserEntity.getId(), paymentUserEntity.getCorpid(), IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_TEAM, paymentUserEntity.getDataId());
//        paasEsModel.update(paymentUserEntity,IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM,paymentUserEntity.getCorpid(),paymentUserEntity.getId(),paymentUserEntity.getDataId());
    }
    
    @Override
    public void contractUserInsert(UserEntity userEntity, Long contractId, Integer isMain) throws XbbException {
    
    }
    
    @Override
    public List<UserTeamEntity> findBaseEntitys(Map<String, Object> map) {
        return paymentSheetUserDao.findBaseEntitys(map);
    }
    
    @Override
    public Integer deleteByContractIdIn(List<Long> contractIdIn, String corpid) throws XbbException {
        return null;
    }
    
    @Override
    public List<Long> getDataIdList(String corpid, Integer isMain, List<String> userId) {
        return null;
    }
    
    @Override
    public void insertBatch(List<PaymentSheetUserEntity> paymentUserEntityList) throws XbbException{
        insertBatch(paymentUserEntityList, WriteRequest.RefreshPolicy.NONE);
    }

    @Override
    public void insertBatch(List<PaymentSheetUserEntity> paymentUserEntityList, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException{
        paymentSheetUserDao.insertBatch(paymentUserEntityList);

        List<PaasFormDataEntity> paasFormDataEntities = transferSubFormHelper.transferUserTeamToFormDataList(IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_TEAM, paymentUserEntityList);

        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PaasFormDataEntity paasFormDataEntity : paasFormDataEntities) {
            insertDTOList.add(paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_TEAM));
        }
        paasEsModel.insertBatch(insertDTOList, refreshPolicy);
    }

    
    @Override
    public void insertBatch(List<PaymentSheetUserEntity> paymentUserEntityList,boolean needThrow) throws XbbException{
        paymentSheetUserDao.insertBatch(paymentUserEntityList);

        List<PaasFormDataEntity> paasFormDataEntities = transferSubFormHelper.transferUserTeamToFormDataList(IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_TEAM, paymentUserEntityList);

        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PaasFormDataEntity paasFormDataEntity : paasFormDataEntities) {
            insertDTOList.add(paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_TEAM));
        }
//        for (PaymentSheetUserEntity paymentUserEntity : paymentUserEntityList) {
//            InsertDTO insertDTO = new InsertDTO();
//            insertDTO.setWaitUntil(WriteRequest.RefreshPolicy.NONE);
//            insertDTO.setEsId(paymentUserEntity.getCorpid() + "_" + paymentUserEntity.getId());
//            insertDTO.setParent(paymentUserEntity.getCorpid() + "_" + paymentUserEntity.getDataId());
//            insertDTO.setSource(BeanUtil.convertBean2Map(paymentUserEntity, false, true));
//            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_TEAM);
//            insertDTOList.add(insertDTO);
//        }
        paasEsModel.insertBatch(insertDTOList, WriteRequest.RefreshPolicy.NONE, needThrow);
    }
    
    @Override
    public void batchUpdateByUserIdIn(String corpid, List<Long> dataIdIn, List<UserTeamEntity> teamEntityList, Integer isMain, Integer del,boolean needThrow) throws XbbException {
        batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, del, needThrow, WriteRequest.RefreshPolicy.NONE);
    }

    @Override
    public void batchUpdateByUserIdIn(String corpid, List<Long> dataIdIn, List<UserTeamEntity> teamEntityList, Integer isMain, Integer del, boolean needThrow, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        paymentSheetUserDao.batchUpdateByIdIn(corpid, dataIdIn, isMain, del);
        List<InsertDTO> insertList = new ArrayList<>();
        for (UserTeamEntity userTeamEntity : teamEntityList) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_TEAM.getType() + "_" + corpid + "_" + userTeamEntity.getId());
            insertDTO.setParent(corpid + "_" + userTeamEntity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(isMain)) {
                JSONObject object = new JSONObject();
                object.put(PaymentSheetTeamEnum.IS_MAIN.getDataAttr(), isMain);
                map.put(StringConstant.JSON_DATA, object);
            }
            if (Objects.nonNull(del)) {
                map.put(ParameterConstant.DEL, del);
            }
            map.put(FieldTypeEnum.UPDATETIME.getAlias(), DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_TEAM);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList, refreshPolicy, needThrow);
    }

    /**
     * 批量更新团队的人员为协同人身份以及协同人的可编辑权限
     *
     * @param corpid
     * @param dataIdIn
     * @param teamEntityList
     * @param isMain
     * @param needThrow
     * @throws XbbException
     */
    @Override
    public void batchUpdateCoAndPerByUserIdIn(String corpid, List<Long> dataIdIn, List<UserTeamEntity> teamEntityList, Integer isMain, boolean needThrow) throws XbbException {
        batchUpdateCoAndPerByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, needThrow, WriteRequest.RefreshPolicy.WAIT_UNTIL);

    }

    @Override
    public void batchUpdateCoAndPerByUserIdIn(String corpid, List<Long> dataIdIn, List<UserTeamEntity> teamEntityList, Integer isMain, boolean needThrow, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        Integer formPermission = teamEntityList.get(BasicConstant.ZERO).getFormPermission();
        paymentSheetUserDao.batchUpdateCoAndPerByUserIdIn(corpid, dataIdIn, isMain, formPermission);
        List<InsertDTO> insertList = new ArrayList<>();
        for (UserTeamEntity userTeamEntity : teamEntityList) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_TEAM.getType() + "_" + corpid + "_" + userTeamEntity.getId());
            insertDTO.setParent(corpid + "_" + userTeamEntity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(isMain)) {
                JSONObject object = new JSONObject();
                object.put(PaymentSheetTeamEnum.IS_MAIN.getDataAttr(), isMain);
                map.put(StringConstant.JSON_DATA, object);
            }
            map.put(FieldTypeEnum.UPDATETIME.getAlias(), DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_TEAM);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList, refreshPolicy, needThrow);
    }

    @Override
    public void deleteByPaymentSheetIds(List<Long> dataIds, String corpid) throws XbbException {
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid",corpid);
        map.put("del",0);
        map.put("paymentSheetIdIn", dataIds);
        List<PaymentSheetUserEntity> paymentSheetUserEntities = findEntitys(map);
        paymentSheetUserDao.deleteByPaymentSheetIds(dataIds, corpid);
        for (PaymentSheetUserEntity entity : paymentSheetUserEntities) {
            paasEsModel.delete(entity.getId(), corpid, IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_TEAM, entity.getDataId());
        }

    }

    /**
     * 编辑协同人表单权限
     *
     * @param paymentSheetUserEntity
     */
    @Override
    public void updateEditFormPer(PaymentSheetUserEntity paymentSheetUserEntity) throws XbbException{
        updateFormTeam(paymentSheetUserEntity);
    }

    @Override
    public void editLabel(PaymentSheetUserEntity paymentSheetUserEntity) throws XbbException{
        updateFormTeam(paymentSheetUserEntity);
    }

    private void updateFormTeam(PaymentSheetUserEntity paymentSheetUserEntity) throws XbbException {
        Long updateTime = DateTimeUtil.getInt();
        paymentSheetUserEntity.setUpdateTime(updateTime);
        paymentSheetUserDao.update(paymentSheetUserEntity);
        InsertDTO insertDTO = new InsertDTO();
        String corpid = paymentSheetUserEntity.getCorpid();
        insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_TEAM.getType() + "_" + corpid + "_" + paymentSheetUserEntity.getId());
        insertDTO.setParent(corpid + "_" + paymentSheetUserEntity.getDataId());
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("updateTime", updateTime);
        insertDTO.setSource(map);
        insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_TEAM);
        paasEsModel.update(insertDTO);
    }

    @Override
    public void batchDelete(String corpid, List<PaymentSheetUserEntity> removeList,boolean needThrow) throws XbbException {
        List<Long> removeIdList = new ArrayList<>();
        removeList.forEach(entity -> removeIdList.add(entity.getId()));
        paymentSheetUserDao.batchDeleteById(corpid, removeIdList);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PaymentSheetUserEntity entity : removeList){
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_TEAM.getType() + "_" + corpid + "_" + entity.getId());
            insertDTO.setParent(corpid + "_" + entity.getDataId());
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_TEAM);
            insertDTO.setIndex(IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_TEAM.getIndex());
            insertDTO.setType(IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_TEAM.getType());
            Map<String,Object> sourceMap = new HashMap<>();
            sourceMap.put(StringConstant.UPDATE_TIME, DateTimeUtil.getInt());
            sourceMap.put(StringConstant.DEL, DelEnum.DELETE.getDel());
            insertDTO.setSource(sourceMap);
            insertDTOList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertDTOList,WriteRequest.RefreshPolicy.NONE,needThrow);
    }
    
    private void deleteBatch(List<Long> idList, String corpid) {
        paymentSheetUserDao.deleteBatch(idList, corpid);
    }

    @Override
    public void disbandedTeamByCustomerId(String corpid, List<Long> customerIdList) throws XbbException {
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put(StringConstant.CORPID, corpid);
        map.put(ParameterConstant.DATA_ID_IN, customerIdList);
        map.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        List<PaymentSheetUserEntity> entitys = findEntitys(map);
        paymentSheetUserDao.disbandedTeamByCustomerId(corpid, customerIdList);
        for (PaymentSheetUserEntity entity : entitys) {
            paasEsModel.delete(entity.getId(), corpid, IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_TEAM, entity.getDataId());
        }
    }

    /**
     * 批量更新回款单团队的删除标识，这边一开始是为了工作流撤回使用 删除标识是6；后面如果其它要使用注意一下
     *
     * @param corpid
     * @param paymentSheetUserEntities
     * @param del
     */
    @Override
    public void deleteBatchUser(String corpid, List<PaymentSheetUserEntity> paymentSheetUserEntities, Integer del) throws XbbException {
        if (CollectionsUtil.isEmpty(paymentSheetUserEntities)) {
            return;
        }
        List<Long> idList = new ArrayList<>();
        List<InsertDTO> insertDTOList = new ArrayList<>();
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put(StringConstant.DEL, del);
        for (PaymentSheetUserEntity entity : paymentSheetUserEntities){
            idList.add(entity.getId());
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_TEAM.getType() + "_" + corpid + "_" + entity.getId());
            insertDTO.setParent(corpid + "_" + entity.getDataId());
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_TEAM);
            insertDTO.setIndex(IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_TEAM.getIndex());
            insertDTO.setType(IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_TEAM.getType());
            insertDTO.setSource(map);
            insertDTOList.add(insertDTO);
        }
        paymentSheetUserDao.deleteBatchByIdList(idList, corpid, del);
        paasEsModel.updateBatch(insertDTOList);
    }
}
